// 班级
const router = require('express').Router()
const db = require('../db')

// 得到班级列表
router.get('/get', (req, res) => {
    let { role, id } = req.query.user
    if (role === 'admin') {
        db.query(' SELECT * FROM class', [], result => {
            res.json({ code: 0, data: result })
        })  //////////// 得到的是所教的班级
    } else if (role === 'teacher') {
        db.query(`SELECT * FROM teacher_class WHERE teacher = '${id}';`, [], result => {
            let params = []
            result.map((item, i) => {
                params[i] = item.class
            })
            db.query(`SELECT * FROM class WHERE id IN(?)`, [params], result2 => {
                let data = []
                result2.map((item) => {
                    data.push(item)
                })
                res.json({
                    code: 0,
                    data
                })
            })
        })
    }
})

// 
router.get('/getName', (req, res) => {
    // db.query(`select classId, className  from  class_course_view WHERE courseId = ${id} group by classId;`, )
    db.query(`select classId, className  from  class_course_view WHERE courseId = ${req.query.courseId} group by classId;`, [], data => {
        res.json({ code: 0, data })
    })

});

// 得到一个班级的所有学生
router.get('/getStudentList', (req, res) => {
    let { classId, page, limit } = req.query
    if (req.query.classId && req.query.user.role !== 'student') {
        db.query(`SELECT count(*) FROM student_view  WHERE  classId = ${classId} `, {}, result => {
            let totalCount = result[0]['count(*)'];
            db.query(`SELECT studentId, studentName, sex, classId, className FROM student_view WHERE classId = ${classId}  LIMIT ${(page - 1) * limit}, ${limit} `, {}, list => {

                res.json({
                    code: 0,
                    page: {
                        currPage: page,
                        pageSize: limit,
                        list,
                        totalCount,
                        totalPage: Math.ceil(totalCount / limit)
                    }
                })
            })
        })
    }
})

module.exports = router